<?php
class get_key {
	private $appid;
	private $appsecret;
	private $access_token_path;
	private $jsapi_ticket_path;
	
	function __construct($appid, $appsecret, $root) {
       $this->appid = $appid;
	   $this->appsecret = $appsecret;
	   $this->access_token_path = $root."/common/access_token.txt";
	   $this->jsapi_ticket_path = $root."/common/jsapi_ticket.txt";
	}
	
	private function write_file($type, $key){
		if($type == 'access_token'){
			$f = fopen($this->access_token_path, "w");
			fwrite($f, $key);
		}
		if($type == 'jsapi_ticket'){
			$f = fopen($this->jsapi_ticket_path, "w");
			fwrite($f, $key);
		}
	}
	
	private function read_file($type){
		if($type == 'access_token'){
			return file_get_contents($this->access_token_path);
		}
		if($type == 'jsapi_ticket'){
			return file_get_contents($this->jsapi_ticket_path);
		}
	}
	
	private function get_file_time($type){
		if($type == 'access_token'){
			$filename = $this->access_token_path;
		}
		if($type == 'jsapi_ticket'){
			$filename = $this->jsapi_ticket_path;
		}
		if (file_exists($filename)){
			if(time() - filemtime($filename) < 7200){
				return true;
			}else{
				return false;
			}
		}else{
		  return false;
		}
	}
	
	public function get_access_token(){
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
		if($this->get_file_time("access_token")){
			return $this->read_file("access_token");
		}else{
			$access_token = file_get_contents($url);
			$data = json_decode($access_token);
			if(json_last_error() == JSON_ERROR_NONE){
				$access_token = $data->access_token;
				$this->write_file("access_token", $access_token);
				return $access_token;
			}else{
				return false;
			}
		}
	}
	
	public function get_jsapi_ticket(){
		if($this->get_file_time("jsapi_ticket")){
			return $this->read_file("jsapi_ticket");
		}else{
			$access_token = $this->get_access_token();
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
			$jsapi_ticket = file_get_contents($url);
			$data = json_decode($jsapi_ticket);
			if(json_last_error() == JSON_ERROR_NONE){
				$jsapi_ticket = $data->ticket;
				$this->write_file("jsapi_ticket", $jsapi_ticket);
				return $jsapi_ticket;
			}else{
				return false;
			}
		}
	}
}